﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace PdfOperator
{
    public partial class FrmImgToPdf : Form
    {
        public FrmImgToPdf()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 打开转换的pdf
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpenPdf_Click(object sender, EventArgs e)
        {
            //判断文件是否存在
            if (!File.Exists(txtSavePath.Text))
            {
                return;
            }
            else
            {
                //存在文件
                System.Diagnostics.Process.Start(txtSavePath.Text);
            }
        }

        /// <summary>
        /// 选择图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelectImgs_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFiles = new OpenFileDialog();
            openFiles.Multiselect = true;
            openFiles.Filter = "图片|*.png;*.jpg;*.jpeg;*.bmp";
            if (openFiles.ShowDialog() == DialogResult.OK)
            {
                string[] filenames = openFiles.FileNames;
                Array.Sort(filenames);
                foreach (string filename in filenames)
                {
                    lstBoxFileList.Items.Add(filename);
                }
            }
        }

        /// <summary>
        /// 选择保存路径
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSavePath_Click(object sender, EventArgs e)
        {
            if (lstBoxFileList.Items.Count < 1)
            {
                MessageBox.Show("请先选择待转换的图片！");
                return;
            }
            SaveFileDialog saveFile = new SaveFileDialog();
            saveFile.Title = "选择保存文件路径";
            saveFile.Filter = "pdf文件|.*pdf";
            saveFile.DefaultExt = ".pdf";
            saveFile.FileName = "图片转PDF1.pdf";
            if (saveFile.ShowDialog() == DialogResult.OK)
            {
                txtSavePath.Text = saveFile.FileName;
            }
        }

        /// <summary>
        /// 开始转换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, EventArgs e)
        {
            if (lstBoxFileList.Items.Count < 1)
            {
                MessageBox.Show("请添加要转换的t图片！");
                return;
            }
            if (string.IsNullOrEmpty(txtSavePath.Text))
            {
                MessageBox.Show("请选择PDF文件保存路径！");
                return;
            }

            List<string> imgList = new List<string>();
            for (int i = 0; i < lstBoxFileList.Items.Count; i++)
            {
                imgList.Add(lstBoxFileList.Items[i].ToString());
            }

            try
            {
                // 创建文档对象
                Document document = document = new Document(iTextSharp.text.PageSize.A4, 19, 19, 25.4f, 25.4f);


                // 创建pdf对象
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(txtSavePath.Text, FileMode.Create));
                document.Open();

                foreach (string imgName in imgList)
                {
                    iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imgName);
                    if (img.Height > iTextSharp.text.PageSize.A4.Height - 25.4f)
                    {
                        img.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 19, iTextSharp.text.PageSize.A4.Height - 25.4f);
                    }
                    else if (img.Width > iTextSharp.text.PageSize.A4.Width - 19)
                    {
                        img.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 19, iTextSharp.text.PageSize.A4.Height - 25.4f);
                    }
                    img.SetAbsolutePosition(0, 0);
                    // img.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE;
                    document.NewPage();
                    writer.DirectContent.AddImage(img);
                }
                document.Close();
                writer.Close();
                MessageBox.Show("完成");
            }
            catch (Exception exp)
            {
                MessageBox.Show("出错：" + exp.Message);
            }
        }


        /// <summary>
        /// 开始拖放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lstBoxFileList_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Link;
                this.lstBoxFileList.Cursor = Cursors.Arrow; //指定鼠标形状   
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        /// <summary>
        /// 接收拖放文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lstBoxFileList_DragDrop(object sender, DragEventArgs e)
        {
            var paths = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetEnumerator();
            while (paths.MoveNext())
            {
                string file = paths.Current.ToString();
                string ext = Path.GetExtension(file).ToLower();
                if (ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".bmp")
                {
                    lstBoxFileList.Items.Add(file);
                }
            }

            this.lstBoxFileList.Cursor = Cursors.Default; //还原鼠标形状 
        }

        /// <summary>
        /// delete键删除列表选中项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lstBoxFileList_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                lstBoxFileList.Items.Remove(lstBoxFileList.SelectedItem);
            }
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
